package vertx;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4J2LoggerFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.templ.thymeleaf.ThymeleafTemplateEngine;

public class StaticVerticle extends AbstractVerticle {
  final InternalLogger logger= Log4J2LoggerFactory.getInstance(StaticVerticle.class);
  Router router;
  //第一步声明一个模板引擎
  ThymeleafTemplateEngine thymeleafTemplateEngine;
  @Override
  public void start(Promise<Void> startPromise) throws Exception {

    router =Router.router(vertx);
    //第二步初始化模板引擎
    thymeleafTemplateEngine=ThymeleafTemplateEngine.create(vertx);
    //整合静态文件，第一步 bootstrap.css robots.txt
    //router.route("/static/*").handler(StaticHandler.create());
    //整合静态文件，自定义访问路径
    router.route("/*").handler(StaticHandler.create());
    router.route("/").handler(
      req -> {
        logger.info("啊啊啊啊啊","来啦");
        //后端传参给前端
        JsonObject entries = new JsonObject();
        entries.put("name","vert.x 2020-10-05");
        //第三步 render 1.JsonObject
        thymeleafTemplateEngine.render(entries,
          "templates/index.html",templates->{
            if (templates.succeeded()){
              req.response()
                //text/plain修改json格式application/json
                .putHeader("content-type", "text/html")
                .end(templates.result());
            } else {

            }
          });

      });


    vertx.createHttpServer().requestHandler(router).listen(8888,http->{
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
